package com.haierp.service.impl;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.haierp.enums.OrderStatus;
import com.haierp.enums.StockUpStatus;
import com.haierp.exception.ErpCommonException;
import com.haierp.exception.InventoryException;
import com.haierp.mapper.ErpOrderMapper;
import com.haierp.mapper.InventoryAreaMapper;
import com.haierp.mapper.InventoryMapper;
import com.haierp.mapper.OuterOrderDetailMapper;
import com.haierp.mapper.PurchaseStorageDetailMapper;
import com.haierp.mapper.TaskDailyDetailMapper;
import com.haierp.model.ErpOrder;
import com.haierp.model.InventoryArea;
import com.haierp.model.InventoryRecord;
import com.haierp.model.InventoryRecord.InventoryType;
import com.haierp.model.ItemSku;
import com.haierp.model.ShippingOrder;
import com.haierp.model.ShippingTrack;
import com.haierp.model.sale.OuterOrder;
import com.haierp.model.sale.OuterOrderDetail;
import com.haierp.service.IErpOrderService;
import com.haierp.service.IInventoryRecordService;
import com.haierp.service.IInventoryService;
import com.haierp.service.IItemSkuService;
import com.haierp.service.IOuterOrderService;
import com.haierp.service.ISequenceUtilService;
import com.haierp.service.IShippingOrderService;
import com.haierp.service.IWarehouseService;
import com.haierp.service.impl.InventoryServiceImpl.WarehouseCollector;
import com.haierp.util.BizResult;
import com.haierp.util.ErpOrderUtil;
import com.haierp.util.JsonPageResult;
import com.haierp.util.JsonResult;
import com.haierp.vo.ErpOrderQueryVO;
import com.wangzhixuan.commons.shiro.ShiroUser;
import com.wangzhixuan.commons.utils.HaiJsonUtils;

@Service("erpOrderService")
public class ErpOrderServiceImpl extends SuperServiceImpl<ErpOrderMapper, ErpOrder>  implements IErpOrderService {
	
	@Autowired
	private ISequenceUtilService sequenceUtilService;
	@Autowired
	private ErpOrderMapper erpOrderMapper;
	@Autowired
	private IItemSkuService itemSkuService;
	@Autowired
	private IInventoryService inventoryService;
	@Autowired
	private IOuterOrderService outerOrderService;
	@Autowired
	private IWarehouseService warehouseService;
	@Autowired
	private OuterOrderDetailMapper outerOrderDetailMapper;
	@Autowired
	private InventoryMapper inventoryMapper;
	@Autowired
	private InventoryAreaMapper inventoryAreaMapper;
	@Autowired
	private PurchaseStorageDetailMapper purchaseStorageDetailMapper;
	@Autowired
	private TaskDailyDetailMapper taskDailyDetailMapper;
	@Autowired
	private IShippingOrderService shippingOrderService;

	@Override
	public void importOuterOrder(OuterOrder order) {
		List<OuterOrderDetail> outerOrderDetails = order.getOuterOrderDetails();
		int i=0;
		for (OuterOrderDetail outerOrderDetail : outerOrderDetails) {
			if(outerOrderDetail.getSkuId()==null) continue;
			insertErpOrder(order, outerOrderDetail, ++i);
		}
	}

	
	@Override
	public void reviewOuterOrder(Long orderId,String type) {
		OuterOrder outerOrder = outerOrderService.queryOuterOrder(orderId);
		if("YZ".equals(type) || "HH".equals(type)){
			outerOrder.setCompanyId(1L);//如果有赞推单直接设置订单company=1
		}
		if("XHS".equals(type)){
			outerOrder.setCompanyId(2L);//如果小红书推单直接设置订单company=2
		}
		if("XHSL".equals(type)){
			outerOrder.setCompanyId(3L);//如果小红书推单直接设置订单company=3
		}
		if(outerOrder!=null){
			importOuterOrder(outerOrder);
		}
	}
	
	@Override
	public JsonPageResult<List<ErpOrder>> queryErpOrders(ErpOrderQueryVO erpOrderQueryVO) {
		JsonPageResult<List<ErpOrder>> erpOrderResult = new JsonPageResult<>();
		if(erpOrderQueryVO.getRemoveOrder() != null) {
			List<String> erpOrderids = new ArrayList<String>();
			List<String> idCards = erpOrderMapper.queryErpOrdersIdCard();
			for (String string : idCards) {
				EntityWrapper<ShippingOrder> entityWrapperpx = new EntityWrapper<ShippingOrder>();
				entityWrapperpx.where("id_card={0} and logistic_company={1} and gmt_create>=DATE_SUB(CURDATE(), INTERVAL 6 DAY)", string, "4PX");
				int numPX = shippingOrderService.selectCount(entityWrapperpx);
				EntityWrapper<ShippingOrder> entityWrapper = new EntityWrapper<ShippingOrder>();
				entityWrapper.where("id_card={0} and logistic_company={1} and gmt_create>=DATE_SUB(CURDATE(), INTERVAL 6 DAY)", string, "邮客");
				int numYK = shippingOrderService.selectCount(entityWrapper);
				if(numPX >= 2 && numYK >= 2) {
					erpOrderids.add(string);
				}
			}
				erpOrderQueryVO.setNoshippingIdcards(erpOrderids);
		}

		// 1、查询总的记录数量
		Integer totalCount = erpOrderMapper.queryErpOrdersCount(erpOrderQueryVO);
		// 2、查询分页记录
		if (totalCount != null && totalCount != 0L) {
			erpOrderResult.buildPage(totalCount, erpOrderQueryVO);
			List<ErpOrder> erpOrders = erpOrderMapper.queryErpOrders(erpOrderQueryVO);
			Map<Long, String> warehouseMap = warehouseService.getWarehouseMap();
			erpOrders.forEach(erpOrder -> {
				erpOrder.setWarehouseName(warehouseMap.get(erpOrder.getWarehouseId()));
			});
			if(erpOrderQueryVO.getPageSize() == 500 || erpOrderQueryVO.getPageSize() == 200) {
				erpOrderResult.setCountTotal(totalCount);
			}
			erpOrderResult.setData(erpOrders);
		} else {
			List<ErpOrder> erpOrders = new ArrayList<>();
			erpOrderResult.setData(erpOrders);
		}
		return erpOrderResult;
	}
	
	@Override
	public List<ErpOrder> queryUnStockUpErpOrders(Long skuId) {
		return erpOrderMapper.queryUnStockUpErpOrders(skuId);
	}

	@Override
	public List<ErpOrder> queryTransStockUpErpOrders(Long skuId) {
		return erpOrderMapper.queryTransStockUpErpOrders(skuId);
	}

	@Override
	public BizResult lockErpOrder(ErpOrder erpOrder) throws InventoryException{
		if(erpOrder.getStatus()!=OrderStatus.INIT.getCode()){
			return BizResult.buildFailed("订单状态错误");
		}
		//未备货订单
		if(erpOrder.getStockStatus()==StockUpStatus.INIT.getCode()||erpOrder.getStockStatus()==StockUpStatus.RELEASED.getCode()){
			if(erpOrder.getWarehouseId()==null){
				List<ErpOrder> erpOrders = Lists.newArrayList();
				erpOrders.add(erpOrder);
				 List<WarehouseCollector> wcs = inventoryService.selectWarehousesByErpOrders(erpOrders);
				 if(CollectionUtils.isNotEmpty(wcs)){
					 inventoryService.lockedInventroy(wcs.get(0));
				 }else{
					 return BizResult.buildFailed("没有库存备货失败");
				 }
			}else{
				return BizResult.buildFailed("没有仓库信息");
			}
		}else{
			if(erpOrder.getStockStatus()!=StockUpStatus.STOCKUP.getCode()&&erpOrder.getStockStatus()!=StockUpStatus.MIX_STOCKUP.getCode()&&erpOrder.getWarehouseId()!=null){
				WarehouseCollector wc = inventoryService.selectWarehousesByErpOrder(erpOrder);
				if(wc!=null){
					 inventoryService.lockedInventroy(wc);
				 }else{
					 return BizResult.buildFailed("没有库存备货失败");
				 }
			}else{
				return BizResult.buildFailed("订单备货状态错误");
			}
			
		}
		return BizResult.buildSuccess();
	}
	
	@Override
	public void lockErpOrderBySkuId(Long skuId) throws InventoryException{
		List<ErpOrder> erpOrders = queryUnStockUpErpOrders(skuId);
		if(erpOrders!=null && erpOrders.size()>0) {
			for (ErpOrder erpOrder : erpOrders) {
				lockErpOrder(erpOrder);
			}
		}
	}
	
	private String genErpOrderNo(){
		Long seqNo = sequenceUtilService.gainERPOSequence();
		return String.format("%sS%08d",LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE), seqNo);
	}
	
	private Long insertErpOrder(OuterOrder order, OuterOrderDetail outerOrderDetail, int index) {
		ItemSku itemSku = itemSkuService.selectById(outerOrderDetail.getSkuId());
		
		ErpOrder erpOrder = new ErpOrder();
		erpOrder.setOuterOrderId(order.getId());
		erpOrder.setCompanyId(order.getCompanyId());//所属公司
		erpOrder.setOuterDetailOrderId(outerOrderDetail.getId());
		erpOrder.setOrderNo(order.getOrderNo());
		erpOrder.setTargetNo(order.getTargetNo());
		erpOrder.setErpNo("O" + order.getOrderNo().substring(1) + String.format("%0"+4+"d", index));
		erpOrder.setStatus(0);
		erpOrder.setStockStatus(0);
		erpOrder.setPurchaseStatus(0);//默认采购状态为正常
		erpOrder.setPayStatus(0);
		erpOrder.setOrderTime(order.getOrderTime());
		erpOrder.setUpc(outerOrderDetail.getUpc());
		erpOrder.setSkuId(outerOrderDetail.getSkuId());
		erpOrder.setSkuCode(outerOrderDetail.getSkuCode());
		erpOrder.setThirdSkuCode(outerOrderDetail.getThirdSkuCode());
		erpOrder.setSkuPic(outerOrderDetail.getSkuPic());
		erpOrder.setLogisticType(outerOrderDetail.getLogisticType());
		erpOrder.setSalesId(order.getSalesId());
		erpOrder.setSalesName(order.getSalesName());
		erpOrder.setItemId(itemSku != null ? itemSku.getItemId() : null);
		erpOrder.setItemName(outerOrderDetail.getItemName());
		erpOrder.setColor(outerOrderDetail.getColor());
		erpOrder.setScale(outerOrderDetail.getScale());
		erpOrder.setFreight(itemSku != null && itemSku.getFreight()!=null ? ((double)itemSku.getFreight()) : null);	//单位：分；此处是预估物流费用,从SKU中获得，此值是根据商品重量、包装规格计算所得
		erpOrder.setWeight(itemSku.getWeight());
		erpOrder.setSalePrice(outerOrderDetail.getSalePrice());
		erpOrder.setQuantity(outerOrderDetail.getQuantity());
		erpOrder.setReceiver(order.getReceiver());
		erpOrder.setAddressDetail(order.getAddressDetail());
		erpOrder.setReceiverCity(order.getReceiverCity());
		erpOrder.setReceiverDistrict(order.getReceiverDistrict());
		erpOrder.setReceiverState(order.getReceiverState());
		erpOrder.setIdCard(order.getIdCard());
		erpOrder.setIdcardPicFront(order.getIdcardPicFront());
		erpOrder.setIdcardPicReverse(order.getIdcardPicReverse());
		erpOrder.setTelephone(order.getTelephone());
		erpOrder.setPostcode(order.getPostcode());
		erpOrder.setRemark(order.getRemark());
		//erpOrder.setLogisticId(outerOrderDetail.get);//缺少字段
		Date now = new Date();
		erpOrder.setGmtCreate(now);
		erpOrder.setGmtModify(now);
		erpOrder.setUserCreate(order.getUserCreate());//子订单加入创建者&修改者
		erpOrder.setUserModify(order.getUserModify());
		Subject subject= SecurityUtils.getSubject();
		ShiroUser user = (ShiroUser)subject.getPrincipal();
		if(user != null) {
			erpOrder.setUserCreate(user.getLoginName());
			erpOrder.setUserModify(user.getLoginName());
		}
		erpOrderMapper.insert(erpOrder);
		return erpOrder.getId();
	}

	@Override
	public void closeErpOrder(ErpOrder erpOrder) throws InventoryException {
		erpOrder.setStatus(OrderStatus.CLOSE.getCode());
		erpOrder.setGmtModify(new Date());
		//备货状态清空占用库存
		if(erpOrder.getStockStatus()!=StockUpStatus.INIT.getCode()){
			inventoryService.releaseInventory(erpOrder);
		}
		//未备货订单显示已取消
		if(erpOrder.getStockStatus() == StockUpStatus.INIT.getCode()) {
			erpOrder.setStockStatus(StockUpStatus.CANCEL.getCode());
		}
		this.baseMapper.updateById(erpOrder);

	}
	
	@Autowired
	private IInventoryRecordService inventoryRecordService;

	@Override
	public void splitErpOrder(ErpOrder erpOrder, int splitCount) throws InventoryException {
		ErpOrder newErpOrder = new ErpOrder();
		BeanUtils.copyProperties(erpOrder, newErpOrder);
		newErpOrder.setId(null);
//		newErpOrder.setErpNo(erpNo);
		newErpOrder.setStatus(OrderStatus.INIT.getCode());
		newErpOrder.setStockStatus(StockUpStatus.INIT.getCode());
		newErpOrder.setPurchaseStatus(0);
		newErpOrder.setGmtModify(new Date());
		newErpOrder.setQuantity(erpOrder.getQuantity()-splitCount);
		newErpOrder.setWarehouseId(null);
		if(erpOrder.isIfSpiltAction()) {
			if(erpOrder.getRemark() != null) {
				newErpOrder.setRemark("(系统自动拆单)" + erpOrder.getRemark());
			} else {
				newErpOrder.setRemark("(系统自动拆单)");
			}
		}
		
		//获取子订单数量便于产生单号
		Map<String, Object> clumnMap = new HashMap<>();
		clumnMap.put("outer_order_id", erpOrder.getOuterOrderId());
		List<ErpOrder> erpOrders = erpOrderMapper.selectByMap(clumnMap);
		newErpOrder.setErpNo("O" + erpOrder.getOrderNo().substring(1) + String.format("%0"+4+"d", erpOrders.size()+1));
		this.baseMapper.insert(newErpOrder);
		
		erpOrder.setQuantity(splitCount);
		erpOrder.setGmtModify(new Date());
//		this.baseMapper.updateById(erpOrder);
		//未备货状态
		if(erpOrder.getStockStatus()==StockUpStatus.INIT.getCode()||erpOrder.getStockStatus()==StockUpStatus.RELEASED.getCode()){
			this.baseMapper.updateById(erpOrder);
			
		}else {//部分备货或者全部备货状态
			List<InventoryRecord>  records = inventoryRecordService.queryByErpOrderId(erpOrder.getId());
			int realBooked = 0;//现货备货数量
			int transBooked = 0;//在途备货数量
			Map<Long,InventoryRecord> realMaps = Maps.newHashMap();//现货备货记录
			Map<Long,InventoryRecord> transMaps = Maps.newHashMap();//在途备货记录
			if(CollectionUtils.isNotEmpty(records)){
				for(InventoryRecord record:records){
					if(record.getInventoryType()==InventoryType.INVENTORY){
						realBooked+=record.getBooked();
						realMaps.put(record.getId(), record);
					}else{
						transBooked+=record.getBooked();
						transMaps.put(record.getId(), record);
					}
				}
			}else{
				throw new InventoryException("无备货记录，数据异常");
			}
			//要拆分的主订单比全部备货数量还大，原来的备货直接给予主订单，新增一条未备货的子订单即可
			if(splitCount>=(realBooked+transBooked)){
				//无剩余备货订单
				for(InventoryRecord record:records){
					record.setQuantity(erpOrder.getQuantity());
					record.setGmtModify(new Date());
				}
				inventoryRecordService.updateBatchById(records);
				//根据备货数量计算订单状态
				ErpOrderUtil.calculateStockStatus(erpOrder,realBooked,transBooked);
				this.baseMapper.updateById(erpOrder);
				//新订单改为未备货
//				this.baseMapper.updateById(newErpOrder);
				
			}else if(splitCount>realBooked){//比现货备货大，现货全部给予主订单。
				int mainReal = realBooked;  //主订单现货
				int subReal = 0;   //子订单现货
				
				int mainTrans = splitCount-realBooked;  //主订单在途
				int subTrans = realBooked+transBooked-splitCount;  //子订单在途
				
				
				//有剩余在途备货订单
				int x = splitCount - realBooked;
				if(!transMaps.isEmpty()){
					for(Long id : transMaps.keySet()){
						InventoryRecord tran = transMaps.get(id);
						if(x>0){
							if(x<tran.getBooked()){
								//拆
								int tx = tran.getBooked()-x;
								//x的数量给主订单，tx的数量给子订单
								//新record初始化
								InventoryRecord newRecord = new InventoryRecord();
								BeanUtils.copyProperties(tran, newRecord);
								newRecord.setId(null);
								newRecord.setGmtCreate(new Date());
								newRecord.setGmtModify(new Date());
								newRecord.setBooked(tx);
								newRecord.setQuantity(newErpOrder.getQuantity());
								newRecord.setErpOrderId(newErpOrder.getId());
								inventoryRecordService.insert(newRecord);
								
								//老record数据更新
								tran.setBooked(x);
								tran.setQuantity(erpOrder.getQuantity());
								tran.setGmtModify(new Date());
								
								x=0;
							}else{
								//不拆，全部给主订单
								x-=tran.getBooked();
								tran.setQuantity(erpOrder.getQuantity());
								tran.setGmtModify(new Date());
							}
							
						}else{
							//剩余在途全部给子订单
							tran.setErpOrderId(newErpOrder.getId());
							tran.setQuantity(newErpOrder.getQuantity());
							tran.setGmtModify(new Date());
						}
					}
				}
				//现货全部给主订单
				if(!realMaps.isEmpty()){
					for(Long id : realMaps.keySet()){
						InventoryRecord real = realMaps.get(id);
						real.setQuantity(erpOrder.getQuantity());
						real.setGmtModify(new Date());
					}
				}
				//更新全部在途或者现货record
				inventoryRecordService.updateBatchById(records);
				ErpOrderUtil.calculateStockStatus(erpOrder,mainReal,mainTrans);
				this.baseMapper.updateById(erpOrder);
				
				newErpOrder.setWarehouseId(erpOrder.getWarehouseId());
				ErpOrderUtil.calculateStockStatus(newErpOrder,subReal,subTrans);
				this.baseMapper.updateById(newErpOrder);
			}else{//从1 <= splitCount <= realBooked 个
//				int mainReal = realBooked;
//				int mainTrans = 0;
				int subReal = realBooked-splitCount; //子订单实际备货数量
				int subTrans = transBooked;//子订单在途备货数量
				
				//有剩余现货备货订单
				int x = splitCount;
				for(Long id : realMaps.keySet()){
					InventoryRecord real = realMaps.get(id);
					if(x>0){
						if(x<real.getBooked()){
							//拆
							int tx = real.getBooked()-x;
							//x的数量给主订单，tx的数量给子订单
							//新record初始化
							InventoryRecord newRecord = new InventoryRecord();
							BeanUtils.copyProperties(real, newRecord);
							newRecord.setId(null);
							newRecord.setGmtCreate(new Date());
							newRecord.setGmtModify(new Date());
							newRecord.setBooked(tx);
							newRecord.setQuantity(newErpOrder.getQuantity());
							newRecord.setErpOrderId(newErpOrder.getId());
							inventoryRecordService.insert(newRecord);
							
							//老record数据更新
							real.setBooked(x);
							real.setQuantity(erpOrder.getQuantity());
							real.setGmtModify(new Date());
							
							x=0;
						}else{
							//不拆，全部给主订单
							x-=real.getBooked();
							real.setQuantity(erpOrder.getQuantity());
							real.setGmtModify(new Date());
						}
					}else{//剩下现货都给子订单
						real.setErpOrderId(newErpOrder.getId());
						real.setQuantity(newErpOrder.getQuantity());
						real.setGmtModify(new Date());
					}
				}
				//在途全部给子订单
				if(!transMaps.isEmpty()){
					for(Long id : transMaps.keySet()){
						InventoryRecord tran = transMaps.get(id);
						tran.setErpOrderId(newErpOrder.getId());
						tran.setQuantity(newErpOrder.getQuantity());
						tran.setGmtModify(new Date());
					}
				}
				erpOrder.setStockStatus(StockUpStatus.STOCKUP.getCode());
				erpOrder.setGmtModify(new Date());
				this.baseMapper.updateById(erpOrder);
				
				newErpOrder.setWarehouseId(erpOrder.getWarehouseId());
				ErpOrderUtil.calculateStockStatus(newErpOrder,subReal,subTrans);
				this.baseMapper.updateById(newErpOrder);
				//更新全部在途或者现货record
				inventoryRecordService.updateBatchById(records);
			}
			//inventoryService.releaseInventory(erpOrder);
			//System.out.println("母类ID===========>"+erpOrder.getId());
			if(erpOrder.isIfSpiltAction()) {
				try {
					inventoryService.releaseInventory(newErpOrder);
				} catch (Exception e) {
					this.logger.info(e.getMessage() + e);
				}
				try {
					BizResult bizResult0 = this.lockErpOrder(newErpOrder);
				} catch (Exception e) {
					this.logger.info(e.getMessage() + e);
				}
			}
		}
	}
	
	@Override
	public List<ErpOrder> queryErpOrderForExcel(ErpOrderQueryVO erpOrderQueryVO) {
		return this.baseMapper.queryErpOrderForExcel(erpOrderQueryVO);
	}
	
	@Override
	public void updateUpcForOrder(ErpOrder erpOrder) {
		this.baseMapper.updateUpcForErpOrder(erpOrder);
		outerOrderDetailMapper.updateUpcForOuterOrderDetail(erpOrder);
		inventoryMapper.updateUpcForInventory(erpOrder);
		inventoryAreaMapper.updateUpcForInventoryArea(erpOrder);
		purchaseStorageDetailMapper.updateUpcForPurchaseStorageDetail(erpOrder);
		taskDailyDetailMapper.updateUpcForTaskDailyDetail(erpOrder);
		
	}
	
	@Override
	public void updateWeightForOrder(ErpOrder erpOrder) {
		this.baseMapper.updateWeightForErpOrder(erpOrder);
		outerOrderDetailMapper.updateWeightForOuterOrderDetail(erpOrder);
	}


	@Override
	public ErpOrder queryHaihuErpOrders(OuterOrderDetail outerOrderDetail) {
		return erpOrderMapper.queryHaihuErpOrders(outerOrderDetail);
	}


	@Override
	public List<ErpOrder> queryHaihuShippingNO(String targetNo, String skuCode) {
		
		return erpOrderMapper.queryHaihuShippingNO(targetNo, skuCode);
	}


	@Override
	public void splithaihuErpOrder(String outerOrderDetailList, String tartgetNO) throws InventoryException {
		String s = outerOrderDetailList.replace("&quot;", "\"");
		List<OuterOrderDetail> outerOrderDetails = HaiJsonUtils.toBean(s, new TypeReference<List<OuterOrderDetail>>() {
		});
		if (CollectionUtils.isNotEmpty(outerOrderDetails)) {
			for (OuterOrderDetail outerOrderDetail : outerOrderDetails) {
				synchronized(this) {
					ErpOrder erpOrder = this.queryHaihuErpOrders(outerOrderDetail);
					if (erpOrder == null) {
						throw new ErpCommonException("拆单数量不能超过订单数量");
					}
					this.splitErpOrder(erpOrder, outerOrderDetail.getQuantity());
					erpOrder.setReceiver("海狐海淘");
					erpOrder.setTelephone("18868810546");
					erpOrder.setReceiverState("浙江省");
					erpOrder.setReceiverCity("杭州市");
					erpOrder.setReceiverDistrict("西湖区");
					erpOrder.setAddressDetail("西斗门路9号福地创业园二期四栋二层");
					erpOrder.setUserCreate("海狐拆单");
					erpOrder.setTargetNo(tartgetNO);
					this.updateSelectiveById(erpOrder);
				}
			}

		} else {
			throw new ErpCommonException("拆单明细不能为空");
		}
	}


	@Override
	public JsonPageResult<List<ErpOrder>> queryOrderNoStockSku(ErpOrderQueryVO erpOrderQueryVO) {
		JsonPageResult<List<ErpOrder>> erpOrderResult = new JsonPageResult<>();
		Integer totalCount = erpOrderMapper.queryOrderNoStockSkuCount(erpOrderQueryVO);
		// 2、查询分页记录
		if (totalCount != null && totalCount != 0L) {
			erpOrderResult.buildPage(totalCount, erpOrderQueryVO);
			List<ErpOrder> erpOrders = erpOrderMapper.queryOrderNoStockSku(erpOrderQueryVO);
			erpOrderResult.setData(erpOrders);
		} else {
			List<ErpOrder> erpOrders = new ArrayList<>();
			erpOrderResult.setData(erpOrders);
		}
		return erpOrderResult;
	}


	@Override
	public void updateShippingTimeLaterOrder() {
		EntityWrapper<ErpOrder> entityWrapper = new EntityWrapper<ErpOrder>();
		entityWrapper.where("status={0} and stock_status={1} and stock_date is not null", 0, 10);
		List<ErpOrder> erpList = this.selectList(entityWrapper);
		for (ErpOrder erpOrder : erpList) {
			Date date = erpOrder.getStockDate();
			Date dateNow = new Date();
			int days = (int) ((dateNow.getTime() - date.getTime()) / (1000 * 3600 * 24));
			if (days >= 3) {
				erpOrder.setPurchaseStatus(3);
				this.updateById(erpOrder);
			}

		}

	}


	@Override
	public void updateErpIdCard(String targNo, String idCard) {
		erpOrderMapper.updateErpIdCard(targNo, idCard);
		
	}


	@Override
	public List<ErpOrder> inventoryYzCount(ErpOrderQueryVO erpOrderQueryVO) {
		return erpOrderMapper.inventoryYzCount(erpOrderQueryVO);
	}
	

}
